<?php
session_start();
include("load-settings.php");

/*if(isset($_SESSION['login_attempts']) && $_SESSION['login_attempts'] >= 5)
{
	if(isset($_SESSION['lockout']) && $_SESSION['lockout'] < time() - (60*15))
		$_SESSION['login_attempts'] = 0;
	else
	{
		$_SESSION['lockout'] = time()+(60*15);
		$_SESSION['login_attempts']++;
		die("Temporarily locked out due to too many login attempts. Please try again in 15 minutes.");
	}
}*/

if(isset($_POST['username']) && isset($_POST['password']))
{
	$username = mysql_real_escape_string($_POST['username']);
	$password = mysql_real_escape_string($_POST['password']);

	$result = mysql_query("SELECT * FROM user WHERE paypal = '$username'");

	

	if(mysql_num_rows($result) == 0)
	{
		if(!isset($_SESSION['login_attempts']))
			$_SESSION['login_attempts'] = 1;
		else
			$_SESSION['login_attempts']++;

		$_SESSION['failure_reason'] = "Account not found.";

		header("Location: login.php");
	}
	else
	{
		$row = mysql_fetch_array($result);
		
		if(crypt($password, $row['password']) != $row['password'])
		{
			if(!isset($_SESSION['login_attempts']))
				$_SESSION['login_attempts'] = 1;
			else
				$_SESSION['login_attempts']++;

			$_SESSION['failure_reason'] = "Password does not match.";

			header("Location: login.php");
		}
		else
		{
			if($row['banned'] == 0)
			{
				$_SESSION['logged_in'] = true;
				$_SESSION['user'] = $row['id'];

				mysql_query("INSERT INTO login_history (user, ip, timestamp) VALUES (".$row['id'].", '".$_SERVER['REMOTE_ADDR']."', ".time().")");

				header("Location: home.php");
			}
			else
			{
				$_SESSION['failure_reason'] = "Banned: ".$row['ban_reason'];

				header("Location: login.php");
			}
		}
	}

	
}
else
{
	if(!isset($_SESSION['login_attempts']))
		$_SESSION['login_attempts'] = 1;
	else
		$_SESSION['login_attempts']++;

	$_SESSION['failure_reason'] = "Account not found.";

	header("Location: login.php");
}
?>